<template>
  <div class="login-container">
    <div class="content-container">
      <div class="logo-container">
        <!-- <h3 class="title">供应商后台管理系统</h3> -->
      </div>
      <div class="form-container">
        <div class="title">账号密码登录</div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="off"
          label-position="left"
        >
          <el-form-item prop="username" :error="accountError">
            <!-- <span class="svg-container">
              <svg-icon icon-class="user" />
            </span> -->
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              clearable
              autocomplete="on"
            />
          </el-form-item>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="password" :error="pwdError">
              <!-- <span class="svg-container">
                <svg-icon icon-class="password" />
              </span> -->
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                class="password-input"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
              <!-- <div class="forget">
                <el-divider direction="vertical" />
                <span @click="dialogVisible = true">忘记密码？</span>
              </div> -->
            </el-form-item>
          </el-tooltip>
          <el-form-item v-if="needValidate">
            <div ref="validatePop" />
          </el-form-item>
          <el-button
            size="medium"
            :loading="loading"
            type="primary"
            class="login-button"
            @click.native.prevent="handleLogin"
          >登录</el-button>
        </el-form>
      </div>
    </div>
    <!-- 忘记密码弹框 -->
    <!-- <el-dialog
      title="忘记密码"
      :visible.sync="dialogVisible"
      center
      width="472px"
      class="forget-pwd"
    >
      <template>
        <p>
          请联系小象优品招商负责人，核对信息后我们会将为您重置密码，并发送到您的邮箱。
        </p>
        <p class="or">或</p>
        <p>发送邮件到 <span>liuwenjuan@basestonedata.com</span></p>
        <p>邮件模板如下：</p>
        <div class="temp">
          <p class="name">Hi，请重置我的供应商账号密码。</p>
          <p>
            用户名：<br>
            供应商名称：<br>
            公司邮箱：<br>
            招商负责人：<br>
            联系电话：
          </p>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogVisible = false"
        >我知道了</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import MX from './mixins/smsCode'
export default {
  name: 'Login',
  mixins: [MX],
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'click', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'click', validator: validatePassword }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      accountError: '',
      pwdError: '',
      dialogVisible: false,
      needValidate: false // 是否需要滑块验证
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },

  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= 'a' && key <= 'z') ||
          (!shiftKey && key >= 'A' && key <= 'Z')
        ) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', {
              ...this.loginForm,
              captchaToken: this.captchaToken,
              authenticate: this.authenticate
            })
            .then(({ token, code, message }) => {
              if (token) {
                this.$router.push({
                  path: this.redirect || '/',
                  query: this.otherQuery
                })
              } else {
                this.pwdError = null
                this.accountError = null
                switch (code) {
                  case 400: // 密码错误
                    this.$nextTick(() => {
                      this.pwdError = message
                    })
                    break
                  case 1101: // 账户已被锁定
                    this.$nextTick(() => {
                      this.accountError = message
                    })
                    break
                  case 300: // 账户不存在
                    this.$nextTick(() => {
                      this.accountError = message
                    })
                    break
                  case 10002: // 安全验证
                    this.needValidate = true
                    this.$nextTick(() => {
                      this.handlerTriggerValidate(
                        this.$refs.validatePop,
                        this.loginForm.username
                      )
                    })
                    break
                  default:
                    this.$message.error(message)
                    break
                }
              }
              // console.log(res)
              this.loading = false
            })
            .catch(err => {
              console.log(err)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #f5f5f5;
$light_gray: #000000;
$cursor: #000000;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 40px;
    width: 100%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 4px;
      padding: 12px 5px 12px 15px;
      // color: $light_gray;
      color: rgba(0, 0, 0, 0.65);
      height: 40px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .password-input {
    width: 70%;
  }
  .el-form-item {
    // border: 1px solid rgba(0, 0, 0, 0.15);
    border: 1px solid #d8dce6;
    border-radius: 4px;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 32px;
    // overflow: hidden;
    &.is-error {
      border: 1px solid #f56c6c;
    }
  }
  .login-button {
    margin-top: 46px;
    width: 100%;
    height: 40px;
    background: #fb3b4b;
    border-radius: 4px;
    // border-radius: 4px 12px 12px 4px;
    font-size: 16px;
  }
}
.forget-pwd {
  .el-dialog__header {
    padding-bottom: 32px;
  }
  .el-dialog__body {
    p {
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
      span {
        color: #ed145b;
      }
      &.or {
        margin: 8px 0;
      }
      &.name {
        margin-bottom: 16px;
      }
    }
    .temp {
      margin-top: 16px;
      width: 392px;
      height: 180px;
      padding: 16px;
      background: rgba(0, 0, 0, 0.02);
      border-radius: 4px;
      border: 1px solid rgba(0, 0, 0, 0.15);
    }
  }
  .el-dialog__footer {
    padding: 40px 0 48px;
  }
}
// 第三方防刷校验
.yp-riddler.yp-riddler-button {
  border: 0 none;
  border-radius: 4px;
}
</style>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
$bg: #f5f7fa;
$dark_gray: #889aa4;
$light_gray: #eee;
input:-webkit-autofill {
  box-shadow: 0 0 0px 1000px white inset !important;
}
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  .content-container {
    display: flex;
    justify-content: space-between;
    width: 800px;
    height: 550px;
    @include ca();
    background-color: #fff;
  }
  .logo-container {
    width: 330px;
    background: url("~@/assets/images/login/login_bgimg@2x.png") center
      no-repeat;
    background-size: 100%;
  }
  .form-container {
    // width: 440px;
    padding: 0 40px;
    flex: 1;
    .title {
      width: 100%;
      padding: 56px 0 16px;
      font-size: 16px;
      font-weight: 600;
      line-height: 24px;
      text-align: center;
      color: rgba(0, 0, 0, 0.65);
      // border-bottom: 1px solid #e8e8e8;
    }
    .forget {
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      span {
        cursor: pointer;
        padding-left: 4px;
        padding-right: 12px;
        font-size: 14px;
        font-weight: 400;
        color: rgba(237, 20, 91, 1);
      }
    }
  }
  .login-form {
    position: relative;
    // height: 100%;
    // max-width: 100%;
    padding: 20px 0 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    font-size: 16px;
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  // .title-container {
  //   position: relative;
  //   .title {
  //     font-size: 26px;
  //     color: $light_gray;
  //     margin: 0px auto 40px auto;
  //     text-align: center;
  //     font-weight: bold;
  //   }
  // }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
